package com.web.wechat.web.admin;

import com.blue.core.auth.DigestUtil;
import com.blue.core.dict.HttpMethod;
import com.blue.http.annotation.Http;
import com.blue.http.message.HttpRequest;
import com.blue.http.message.View;
import com.web.base.user.exception.UserException;
import com.web.base.user.facade.UserFacade;
import com.web.base.user.message.UserRequest;
import com.web.base.user.message.UserResponse;
import com.web.base.valid.UserPassword;
import com.web.core.util.Const;
import com.web.wechat.global.model.User;
import com.web.wechat.global.util.HttpContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;

/**
 * 安全设置
 *
 * @author zhengjin
 * @since 1.0 2018年06月27日
 */
@Controller("adminSecurityController")
@Http(url = "/admin/security")
public class SecurityController
{
	@Autowired
	private UserFacade userFacade;
	@Resource
	private HttpContext httpContext;

	public SecurityController()
	{
	}

	@Http(url = "/index")
	public View index(HttpRequest request)
	{
		return View.createBuilder().setView("/admin/security/index")
				.put(Const.FTL_TITLE, "安全设置")
				.build();
	}

	@Http(url = "/password", method = HttpMethod.GET)
	public View passwordGet(HttpRequest request)
	{
		return View.createBuilder().setView("/admin/security/password")
				.put(Const.FTL_TITLE, "修改密码")
				.build();
	}

	@Http(url = "/password", method = HttpMethod.POST)
	public void passwordPost(HttpRequest request)
	{
		User user = httpContext.getUser(request);
		UserRequest userRequest = request.getPostObject(UserRequest.class, UserPassword.class);
		userRequest.setOldPassword(DigestUtil.sha1(userRequest.getOldPassword()));
		if (!user.getPassword().equals(userRequest.getOldPassword()))
			throw new UserException("旧密码错误");

		UserRequest userRequest2 = new UserRequest();
		userRequest2.setId(user.getId());
		userRequest2.setName(user.getName());
		userRequest2.setPassword(userRequest.getPassword());
		UserResponse response = userFacade.update(userRequest2);
		httpContext.setUser(request, User.toUser(response));
	}


}
